package me
import grails.converters.JSON
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
import groovy.sql.Sql
import groovy.json.*
import groovy.json.JsonSlurper

class FileController {

	def dataSource

    def getTreeFile={id,cbFlag->
        def results = []
        def subs = []
        if (id==null) {
            subs = ChartFile.findAll("from ChartFile where parentFileId is null and userLoginId = :userLoginId",
            [userLoginId:session.userLogin.id as Integer])
        } else {
            subs = ChartFile.findAll("from ChartFile where parentFileId=:parentFileId and userLoginId = :userLoginId",
            [parentFileId:id,userLoginId:session.userLogin.id as Integer])
        }

        subs.each{
            def hm = [:]
            hm.id = it.id
            hm.fileName = it.fileName 
            hm.parentFileId = it.parentFileId
            hm.token = it.token
            hm.isDir = it.isDir
            hm.dateCreated = it.dateCreated
            hm.lastUpdated = it.lastUpdated
            hm.leaf = !it.isDir
            if (cbFlag!=null&&cbFlag==true) {
                hm.checked=false
            }

            hm.children = getTreeFile(it.id as Integer,cbFlag)
            results.add(hm)
        }
        return results
    }


    def store() { 
    	def results

        if(params.cbFlag==null) {
            results = getTreeFile(null,false)
        } else {
            results = getTreeFile(null,true)
        }

        render results  as JSON
    }

    def createdir() { 
        

    }

    def move(){
        def results = [success:true]
        def sql = new Sql(dataSource)
        
        def cf = sql.rows("select * from chart_file where id=?",params.id)
        def fileName = cf[0].file_name
        println fileName

        def rows = sql.rows("select * from chart_file where file_name=? and parent_file_id=?",
        [fileName,params.parentFileId])
        println(rows)
        if (rows.size()!=0) {
            sql.execute("delete from chart_file where file_name=? and parent_file_id=?",
            [fileName,params.parentFileId])
            sql.execute("update chart_file set parent_file_id=? where id=?",[params.parentFileId,params.id])
        } else {
            sql.execute("update chart_file set parent_file_id=? where id=?",[params.parentFileId,params.id])
        }
        

        render results  as JSON
    } 

    def rename() {
        def results = [success:true]
        def sql = new Sql(dataSource)
        def id = params.id
        def fileName = params.fileName
        def isDir = params.isDir
        def parentFileId = params.parentFileId
        isDir = isDir=="true"?1:0
        def rows 
        if (parentFileId==null || parentFileId=="") {
            rows = sql.rows("select * from chart_file where file_name=? and is_dir=? and parent_file_id is null and user_login_id=?",
            [fileName,isDir,session.userLogin.id])
        } else {
            rows = sql.rows("select * from chart_file where file_name=? and is_dir=? and parent_file_id=?  and user_login_id=?",
            [fileName,isDir,parentFileId,session.userLogin.id])
        }
        if (rows.size()!=0) {
            results = [success:false,message:"文件名已存在"]
        } else {
            sql.execute("update chart_file set file_name=? where id=?",[fileName,id])
        }
        render results  as JSON
    }

    def delete() { 
        def sql = new Sql(dataSource)
        def results = [success:true]
        sql.execute("delete from chart_file where id = ?",params.id)
        sql.execute("delete from chart_file where parent_file_id = ?",params.id)
    }
    
    def paste() {
        def sql = new Sql(dataSource)
        def results = [success:true]
        def cf = ChartFile.findById(params.id)
        def uuid = sql.rows("SELECT UUID() as uuid")[0].uuid.replace("-","")

        def rows 
        if (params.parentFileId==null||params.parentFileId=="") {
            rows = sql.rows("select * from chart_file where parent_file_id is null and file_name=?",
            [params.fileName])
        } else {
            rows = sql.rows("select * from chart_file where parent_file_id = ? and file_name=?",
            [params.parentFileId,params.fileName])
        }
        
        if (rows.size()!=0) {
            results = [success:false,message:"文件名已存在，请重新命名"]
        } else {
            def chartFile = new ChartFile(fileName:params.fileName,chartSql:cf.chartSql,chartDatasource:cf.chartDatasource,
            chartSource:cf.chartSource,themeId:cf.themeId,
            displayTable:cf.displayTable,token:uuid,isDir:cf.isDir,parentFileId:params.parentFileId,
            rowMode:cf.rowMode,dynamicSeries:cf.dynamicSeries,tableThemeId:cf.tableThemeId,refreshTime:cf.refreshTime,
            remoteUrl:cf.remoteUrl,userLoginId:cf.userLoginId)
            try { 
                chartFile.save(failOnError:true,flush:true) 
            } catch (e) {
                println e
            }
        }
       
        render results  as JSON
    }

    def save() { 
        def sql = new Sql(dataSource)
        def results = [success:true]
        def oldChartId = params.oldChartId
        //println params.isDir
        if (params.id==null || params.id=="") {
            def rows  
            if (params.parentFileId==null||params.parentFileId=="") {
                rows = sql.rows("select * from chart_file where file_name=? and parent_file_id is null and is_dir = ?  and user_login_id=?",
                [params.fileName,(params.isDir=="true"?1:0),session.userLogin.id])
            } else {
                rows = sql.rows("select * from chart_file where file_name=? and parent_file_id=? and is_dir=?  and user_login_id=?",
                [params.fileName,params.parentFileId,(params.isDir=="true"?1:0),session.userLogin.id])
            }
            
            if (rows.size()!=0) {
                if (params.isDir=="true") {
                    results = [success:false,message:'目录已存在,请重新命名']
                } else {
                    def chartFile = ChartFile.findById(rows[0].id)
                    chartFile.fileName = params.fileName    
                    chartFile.isDir = false
                    //chartFile.token = params.token 
                    chartFile.parentFileId = (params.parentFileId==null||params.parentFileId=="")?null:(params.parentFileId as Integer)  
                    chartFile.chartDatasource = (params.chartDatasource&&params.chartDatasource!="")?(params.chartDatasource as Integer):null 
                    chartFile.themeId = (params.themeId==null||params.themeId=="")?null:(params.themeId as Integer)  
                    chartFile.tableThemeId = (params.tableThemeId==null||params.tableThemeId=="")?null:(params.tableThemeId as Integer)  
                    chartFile.chartSource = (params.chartSource==null||params.chartSource=="")?"{}":params.chartSource
                    chartFile.chartSql = params.chartSql  
                    chartFile.remoteUrl = params.remoteUrl  
                    chartFile.userLoginId = session.userLogin.id 
                    chartFile.displayTable = (params.displayTable=="true"?1:0)
                    chartFile.rowMode = (params.rowMode=="true"?1:0)
                    chartFile.dynamicSeries = (params.dynamicSeries=="true"?1:0)
                    chartFile.remoteAdapterId = (params.nowRemoteAdapterId==null||params.nowRemoteAdapterId=="")?null:(params.nowRemoteAdapterId as Integer)
                    chartFile.refreshTime = (params.refreshTime==null||params.refreshTime=="")?0:(params.refreshTime as Integer) 
                    try {
                        chartFile.save(failOnError: true,flush: true) 
                    } catch (e) {
                        println e
                    }

                    
                    sql.execute("delete from chart_event where chart_id=?",chartFile.id)
                    def chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"click",eventSource:params.eventClickSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"dblclick",eventSource:params.eventDblclickSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mousedown",eventSource:params.eventMousedownSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mousemove",eventSource:params.eventMousemoveSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mouseup",eventSource:params.eventMouseupSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mouseover",eventSource:params.eventMouseoverSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mouseout",eventSource:params.eventMouseoutSource)
                    chartEvent.save(failOnError:true,flush:true) 

                    results.chartFile = chartFile

 
                    if (oldChartId!=null && oldChartId!="" && (oldChartId as Integer)!=rows[0].id) {
                        sql.execute("delete from chart_param where chart_id=?",[rows[0].id])
                        sql.rows("select * from chart_param where chart_id=?",oldChartId as Integer).each{
                            sql.execute("insert into chart_param(param_name,param_type,param_default,chart_id) values(?,?,?,?)",
                            [it.param_name,it.param_type,it.param_default,rows[0].id])
                        }
                    }
                    
                    //def slurper = new JsonSlurper()
                    //results.chartSource = JsonOutput.toJson(slurper.parseText(chartFile.chartSource))
                }

            } else {

                if (params.isDir=="true") {
                    def chartFile = new ChartFile(fileName:params.fileName,isDir:true,
                    parentFileId:params.parentFileId,userLoginId:session.userLogin.id)
                    try {
                        chartFile.save(failOnError: true,flush: true) 
                    } catch (e) {
                        println e
                    }
                    results.chartFile = chartFile
                } else {
                   
                    def chartFile = new ChartFile(fileName:params.fileName,chartSql:params.chartSql,chartDatasource:(params.chartDatasource&&params.chartDatasource!="")?(params.chartDatasource as Integer):null,
                    chartSource:(params.chartSource==null||params.chartSource=="")?"{}":params.chartSource,themeId:params.themeId,
                    displayTable:(params.displayTable=="true"?true:false),token:params.token,isDir:false,parentFileId:params.parentFileId,
                    rowMode:(params.rowMode=="true"?true:false),dynamicSeries:(params.dynamicSeries=="true"?true:false),
                    remoteAdapterId:(params.nowRemoteAdapterId==null||params.nowRemoteAdapterId=="")?null:(params.nowRemoteAdapterId as Integer),
                    tableThemeId:(params.tableThemeId==null||params.tableThemeId=="")?null:(params.tableThemeId as Integer),
                    refreshTime:(params.refreshTime?params.refreshTime:0),remoteUrl:params.remoteUrl,userLoginId:session.userLogin.id)
                    try { 
                        chartFile.save(failOnError:true,flush:true) 
                    } catch (e) {
                        println e
                    }
                  
                    def chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"click",eventSource:params.eventClickSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"dblclick",eventSource:params.eventDblclickSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mousedown",eventSource:params.eventMousedownSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mousemove",eventSource:params.eventMousemoveSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mouseup",eventSource:params.eventMouseupSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mouseover",eventSource:params.eventMouseoverSource)
                    chartEvent.save(failOnError:true,flush:true) 
                    chartEvent = new ChartEvent(chartId:chartFile.id,eventType:"mouseout",eventSource:params.eventMouseoutSource)
                    chartEvent.save(failOnError:true,flush:true) 

                    results.chartFile = chartFile    

                    if (oldChartId!=null && oldChartId!="") {

                        sql.rows("select * from chart_param where chart_id=?",oldChartId as Integer).each{
                            sql.execute("insert into chart_param(param_name,param_type,param_default,chart_id) values(?,?,?,?)",
                            [it.param_name,it.param_type,it.param_default,chartFile.id])
                        } 
                    }
                }
                
            }

            
        } else {

            
        }



        render results  as JSON
    }
   	
}
